using Microsoft.ML;
using Microsoft.ML.Data;
using System.Collections.Generic;
using System.Linq;

namespace AdmissionQA.Application.Common
{
    /// <summary>
    /// 文本向量化服务，基于ML.NET TF-IDF
    /// </summary>
    public interface ITextEmbeddingService
    {
        float[] GetVector(string text);
    }
    public class TextEmbeddingService : ITextEmbeddingService
    {
        private readonly MLContext _mlContext;
        private readonly ITransformer _model;

        public TextEmbeddingService(IEnumerable<string> corpus)
        {
            _mlContext = new MLContext();
            var data = _mlContext.Data.LoadFromEnumerable(corpus.Select(t => new TextData { Text = t }));
            var pipeline = _mlContext.Transforms.Text.FeaturizeText(
                outputColumnName: "Features",
                inputColumnName: nameof(TextData.Text));
            _model = pipeline.Fit(data);
        }

        public float[] GetVector(string text)
        {
            var data = new List<TextData> { new TextData { Text = text } };
            var dv = _mlContext.Data.LoadFromEnumerable(data);
            var transformed = _model.Transform(dv);
            var featuresColumn = transformed.GetColumn<float[]>("Features");
            var vector = featuresColumn.First();
            Console.WriteLine($"[DEBUG] Features length: {vector.Length}");
            return vector;
        }

        private class TextData
        {
            public string Text { get; set; } = null!;
        }
    }
}